<template>
  <div class="zb-pro-table">
    <div class="header">
      <el-form :inline="true" class="search-form" :model="query" ref="ruleFormRef">
        <template v-for="(item, index) in formSearchData" :key="index">
          <el-form-item
            v-if="!item.hidden"
            :label="item.label"
            v-show="isExpand ? isExpand : index < defalutMaxSearchCount"
          >
            <template v-if="item.valueType === 'input'">
              <el-input
                v-model="query[item.name]"
                :placeholder="`请输入${item.label}`"
                :clearable="item.clearable ? item.clearable : true"
              />
            </template>
            <template v-else-if="item.valueType === 'select'">
              <el-select
                style="width: 100%"
                v-model="query[item.name]"
                :placeholder="`请选择${item.label}`"
                :clearable="item.clearable ? item.clearable : true"
              >
                <el-option
                  v-for="ite in item.options"
                  :key="ite[item.prop.value]"
                  :label="ite[item.prop.label]"
                  :value="ite[item.prop.value]"
                />
              </el-select>
            </template>
            <template v-else-if="item.valueType === 'date'">
              <el-date-picker
                v-model="query[item.name]"
                type="date"
                :placeholder="`请选择${item.label}`"
                :disabled-date="item.disabledDate"
                :clearable="item.clearable ? item.clearable : true"
                :format="item.format ? item.format : 'YYYY-MM-DD'"
                :value-format="item.valueFormat ? item.valueFormat : 'YYYY-MM-DD'"
              />
            </template>
          </el-form-item>
        </template>
      </el-form>
      <div class="search">
        <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
        <el-button @click="reset(ruleFormRef)" v-if="formSearchData.some((t) => !t.hidden)"
          >重置</el-button
        >
        <el-button
          link
          type="primary"
          @click="isExpand = !isExpand"
          v-if="formSearchData.length > defalutMaxSearchCount"
          >{{ isExpand ? '合并' : '展开'
          }}<el-icon>
            <arrow-down v-if="!isExpand" />
            <arrow-up v-else /> </el-icon
        ></el-button>
      </div>
    </div>
    <!----------底部---------------------->
    <div class="footer">
      <!-----------工具栏操作工具----------------->
      <div class="operator">
        <slot name="btn"></slot>
      </div>
      <!-- ------------表格--------------->
      <div class="table">
        <el-table
          class="zb-table"
          v-loading="loading"
          @selection-change="(val) => emit('selection-change', val)"
          :data="listData"
          :border="true"
          :row-class-name="rowClassName"
          :cell-class-name="cellClassName"
        >
        <el-table-column v-if="showCheckbox" type="selection" />
          <template v-for="item in columns">
            <el-table-column
              v-if="item.type"
              :type="item.type"
              :width="item.width"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
              :sortable="item.sortable"
            />
            <el-table-column
              v-else
              :prop="item.name"
              :width="item.width"
              :align="item.align != null ? item.align : 'center'"
              :fixed="item.fixed"
              :label="item.label"
              :sortable="item.sortable"
            >
              <template #default="scope">
                <span v-if="!item.slot">{{ scope.row[item.name] }}</span>
                <slot v-else :name="item.name" :item="item" :row="scope.row"></slot>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <!-- ------------分页--------------->
      <div class="pagination">
        <el-pagination
          v-model:currentPage="query.pageindex"
          :page-size="query.pagesize"
          background
          :layout="paginationLayout"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- layout="total, prev, pager, next" -->
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  // 防抖函数
  import useDebounce from '@/utils/useDebounce'
  import { SearchModel, SearchPropModel, ColumnModel } from './type'
  import { computed, ref, onMounted, watch } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  const ruleFormRef = ref<FormInstance>()
  const emit = defineEmits([
    'queryEnd',
    'reset',
    'onSubmit',
    'selection-change',
    'handleCurrentChange',
    'handleSizeChange',
  ])
  let props = defineProps({
    showCheckbox:{
      type: Boolean,
      default: false,
    },
    columns: {
      type: Array<ColumnModel>,
      default: () => [],
    },
    searchs: {
      type: Array<SearchModel>,
      default: () => [],
    },
    needLoading: {
      type: Boolean,
      default: true,
    },
    // 默认展示最多的查询条件
    defalutMaxSearchCount: {
      type: Number,
      default: 3,
    },
    queryApiName: {
      type: String,
      default: '',
    },
    delApiName: {
      type: String,
      default: '',
    },
    paginationLayout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper',
    },
    getData: {
      type: Function,
      default: null,
    },
    dataPath: {
      type: String,
      default: 'records',
    },
    rowClassName: {
      type: Function || String,
      default: '',
    },
    cellClassName: {
      type: Function || String,
      default: '',
    },
    defaultPageSize: {
      type: Number,
      default: 10,
    },
  })

  import { reactive } from 'vue'
  import { number } from 'echarts'

  let obj = {}
  let search = []
  // for (let item of props.columns) {
  //   if (item.inSearch) {
  //     obj[item.name] = null
  //   }
  //   if (item.inSearch) {
  //     search.push(item)
  //   }
  // }
  // watch(
  //   () => props.searchs,
  //   (newVal, oldVal) => {
  //     for (let item of newVal) {
  //       if (item.optionsApi) {
  //         api[item.optionsApi]()
  //           .then((res) => {
  //             console.log(res)
  //           })
  //           .catch((err) => {})
  //       }
  //       if (item.hide) {
  //       } else {
  //         search.push(item)
  //       }
  //     }
  //   },
  // )
  for (let item of props.searchs) {
    if (item.optionsApi) {
      api[item.optionsApi]()
        .then((res) => {
          if (res.success) {
            item.options = res.data
          }
        })
        .catch((err) => {})
    }
    if (item.hidden) {
    } else {
      search.push(item)
    }
  }

  const initData = () => {
    search = []
    for (let item of props.searchs) {
      if (item.optionsApi) {
        api[item.optionsApi]()
          .then((res) => {
            if (res.success) {
              item.options = res.data
            }
          })
          .catch((err) => {})
      }
      search.push(item)
    }
    formSearchData.value = search
    reset(undefined)
  }

  const formSearchData = ref(search)
  const formInline = reactive(obj)

  const query = reactive({
    pageindex: 1,
    pagesize: props.defaultPageSize,
  })

  /**
   * 查询
   */
  const onSubmit = () => {
    getData()
    // emit('onSubmit', formInline)
  }

  /**
   * 重置
   * @param formEl
   */
  const reset = (formEl: FormInstance | undefined) => {
    formSearchData.value.forEach((item) => {
      formInline[item.name] = null
      query[item.name] = item.default ? item.default : ''
    })
    getData()
    // emit('reset')
  }

  const deleteAction = (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(() => {
        if (props.delApiName) {
          api[props.delApiName]()
            .then((res) => {
              listData.value = listData.value.filter((item) => item.id !== row.id)
              ElMessage.success('删除成功')
            })
            .catch((err) => {})
        }
      })
      .catch(() => {})
  }

  const loading = ref(false)
  import * as api from '@/api'
  const listData = ref([])
  const total = ref(0)
  const getData = () => {
    loading.value = props.needLoading ? true : false
    if (props.queryApiName) {
      useDebounce(() => {
        api[props.queryApiName](query)
          .then((res) => {
            emit('queryEnd', res)
            if (res.success) {
              listData.value = res.data[props.dataPath]
              total.value = res.data.recordcount
            }
          })
          .catch((err) => {})
          .finally(() => {
            loading.value = false
          })
      })
    }
    if (props.getData) {
      props
        .getData(query)
        .then((res) => {
          listData.value = res.data[props.dataPath]
          total.value = res.data.recordcount
        })
        .catch((err) => {})
        .finally(() => {
          loading.value = false
        })
    } else {
    }
  }

  // 收缩展开
  const isExpand = ref(false)
  const handleSizeChange = (val: number) => {
    query.pagesize = val
    getData()
  }
  const handleCurrentChange = (val: number) => {
    query.pageindex = val
    getData()
  }

  onMounted(() => {
    getData()
  })
  defineExpose({ initData, getData })
</script>
<style scoped lang="scss">
  .edit-input {
    padding-right: 100px;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
  .zb-pro-table {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .header {
      display: flex;
      padding: 16px 16px 0 16px;
      margin-bottom: 16px;
      border-radius: 4px;
      background: white;
      box-shadow: 0 0 12px rgb(0 0 0 / 5%);
      .search-form {
        flex: 1;
        ::v-deep {
          .el-input--default {
            width: 200px;
          }
        }
      }
      .search {
        flex-shrink: 0;
        white-space: nowrap;
        margin-bottom: 18px;
      }
    }
    .footer {
      flex: 1;
      display: flex;
      padding: 16px;
      flex-direction: column;
      border-radius: 4px;
      overflow: hidden;
      background: white;
      box-shadow: 0 0 12px rgb(0 0 0 / 5%);
      min-height: 300px;
      .operator {
        margin-bottom: 15px;
      }
      .table {
        position: relative;
        flex: 1;
      }
      .zb-table {
        position: absolute;
        height: 100%;
      }
    }
    ::v-deep {
      .el-table__header th {
        font-size: 15px;
        font-weight: 700;
        color: #252525;
      }
    }
    .pagination {
      width: 100%;
      display: flex;
      justify-content: center;
      padding-top: 20px;
      box-sizing: border-box;
    }
  }
</style>
